import {
	ref
} from "vue";
import usePagination from "@/composable/hooks/usePagination.js";
import {
	onPullDownRefresh,
	onReachBottom
} from "@dcloudio/uni-app"

function useRefreshablePagination(fetchData, options = {}) {
	const {
		initialLoad = true
	} = options;
	const {
		dataList,
		isLoading,
		isEmpty,
		hasMore,
		loadMore,
		loadMoreStatus,
		initialLoadData
	} = usePagination(fetchData, {
		initialLoad
	});
	// 是否正在刷新
	const isRefreshing = ref(false);

	// 下拉刷新函数
	const refresh = async () => {
		if (isRefreshing.value || isLoading.value) return;
		isRefreshing.value = true;
		try {
			// 重置页码和数据列表
			const page = 1;
			const pageSize = 10;
			const response = await fetchData(page, pageSize);
			const newData = response.data;
			dataList.value = newData;
			if (newData.length < pageSize) {
				hasMore.value = false;
			} else {
				hasMore.value = true;
			}
			// 重置当前页码
			const currentPage = ref(2);
		} catch (error) {
			console.error('刷新数据失败:', error);
		} finally {
			isRefreshing.value = false;
		}
	};

	onPullDownRefresh(async () => {
		await refresh();
		uni.stopPullDownRefresh();
	})

	onReachBottom(() => {
		loadMore();
	})

	// if (initialLoad) {
	// 	// uni.startPullDownRefresh();
	// 	refresh();
	// }

	return {
		dataList,
		isLoading,
		isEmpty,
		hasMore,
		loadMore,
		loadMoreStatus,
		initialLoadData,
		isRefreshing,
		refresh
	};
}

export default useRefreshablePagination;